package com.qian2.pricesharingapplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.lb2.JSONParser;
import com.example.pricesharingapplication.R;

import android.R.anim;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class History extends ListActivity {

	private static final String TAG_SUCCESS = "success";
	private static final String TAG_PRODUCT = "product";
	private static final String TAG_QUOTATION = "quotation";
	private static final String TAG_UID = "uid";
	private static final String TAG_NAME = "name";
	private static final String TAG_DATE = "date";
	private static final String TAG_SHOPNAME = "shopname";
	private static final String TAG_SHOPADDRESS = "shopAddress";
	private static final String TAG_QUANTITY = "quantity";
	private static final String TAG_PRICE = "price";
	private static final String TAG_REVIEW = "review";
	private static final String TAG_RATING = "rating";

	String uid;

	ArrayList<HashMap<String, String>> historylist;

	private static final String url_history = "http://wwwfyp.cse.ust.hk:7117/get_history_list.php";
	JSONParser jsonParser = new JSONParser();

	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_history);
		System.out.println("History.onCreate(): Start GetHistoryList()");

		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		historylist = new ArrayList<HashMap<String, String>>();

		new GetHistoryList().execute();
		// launching Edit Product Screen

	}

	class GetHistoryList extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		/**
		 * Getting Qutation List in background thread
		 * 
		 * */
		ListAdapter adapter;

		@Override
		protected String doInBackground(String... params) {

			// updating UI from Background Thread
			runOnUiThread(new Runnable() {

				public void run() {
					// Check for success tag
					int success;
					try {
						// Building Parameters
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						String email = MainActivity.sharedpreferences
								.getString(MainActivity.Email, "");

						System.out
								.println("History.GetHistoryList.doInBackground(...).new Runnable() {...}.run(): Email  "
										+ email);
						if (email == null) {
							System.out.println("No email");
							return;
						}

						params.add(new BasicNameValuePair("email", email));

						if (!isOnline())
							return;

						JSONObject json = jsonParser.makeHttpRequest(
								url_history, "POST", params);

						// check your log for json response
						System.out.println("History List: " + json.toString());

						// json success tag
						success = json.getInt(TAG_SUCCESS);
						if (success == 1) {
							// successfully received product details
							JSONArray quotationObj = json
									.getJSONArray(TAG_QUOTATION); // JSON Array

							// get first product object from JSON Array

							historylist.clear();
							for (int i = 0; i < quotationObj.length(); i++) {
								JSONObject c = quotationObj.getJSONObject(i);
								// adding each child node to HashMap key =>
								// value

								// creating new HashMap
								HashMap<String, String> map1 = new HashMap<String, String>();

								// adding each child node to HashMap key =>
								// value
								map1.put(TAG_UID, c.getString(TAG_UID));
								map1.put(TAG_NAME, c.getString(TAG_NAME));
								map1.put(TAG_DATE, c.getString(TAG_DATE)
										.substring(0, 10));
								map1.put(TAG_SHOPNAME,
										c.getString(TAG_SHOPNAME));
								map1.put(TAG_SHOPADDRESS,
										c.getString(TAG_SHOPADDRESS));
								map1.put(TAG_QUANTITY,
										c.getString(TAG_QUANTITY));

								map1.put(TAG_PRICE, c.getString(TAG_PRICE));
								map1.put(TAG_REVIEW, c.getString(TAG_REVIEW));
								
								String tempString = c.getString(TAG_RATING);
								if( !tempString.equals(null)){
									tempString = tempString + "/5"; 
								}
								map1.put(TAG_RATING, tempString);

								//map1.put(TAG_RATING, c.getString(TAG_RATING));

								// adding HashList to ArrayList
								historylist.add(map1);
							}

						} else {
							// no history
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			System.out.println("ProductPage.GetQutationList.onPostExecute()");
			ListAdapter adapter = new SimpleAdapter(History.this, historylist,
					R.layout.activity_history_list, new String[] { TAG_UID,
							TAG_NAME, TAG_DATE, TAG_PRICE, TAG_SHOPNAME,
							TAG_SHOPADDRESS, TAG_RATING, TAG_REVIEW },
					new int[] { R.id.uid, R.id.historyname, R.id.historydate,
							R.id.historyprice, R.id.historyshopname,
							R.id.historyshopaddress, R.id.historyrating,
							R.id.historyreview });
			// updating listview
			setListAdapter(adapter);
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		String uid = ((TextView) v.findViewById(R.id.uid)).getText()
				.toString();
		//TODO
		if (!uid.equals("Server_error") && !uid.equals("No_network")){
			// Starting new intent
			Intent in = new Intent(getApplicationContext(),
					ProductPage.class);
			// sending upc to next activity
			in.putExtra(TAG_UID, uid);
			System.out.println("History.onListItemClick() uid : "+ uid);
			// starting new activity and expecting some response back
			startActivityForResult(in, 100);
		}
	}
}
